package yjj;

import yjj.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/yjjlogin")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 使用
        //req.setCharacterEncoding("UTF-8");
        String username = new String(req.getParameter("u").getBytes("ISO-8859-1"), "UTF-8");
        //String username = req.getParameter("u");
        String password = req.getParameter("p");
        System.out.println("username = "+username);
        System.out.println("password = "+password);
        String code = req.getParameter("y");
        HttpSession session = req.getSession();
        Object yy = session.getAttribute("yy");
        boolean isTrue = code != null && code.equals(yy);
        if (!isTrue){
            //输入验证码和存储在session中的验证码不一致
            PrintWriter writer = resp.getWriter();
            writer.write("code is error");
            writer.flush();
            writer.close();
            return;
        }
        //查询数据框，验证账号密码的存在性
        String sql = "SELECT id FROM `user` WHERE username = ? AND `password` = MD5(?)";
        Integer id = JdbcUtils.select(sql, Integer.class, username, password);
        if(id!=null &&id>0){
            // 当凭借账号和密码成功查询到id的时候，将其存储到session中
            session.setAttribute("UID",id);
            // 重定向到首页
            resp.sendRedirect("/yjj/index.jsp");
        }else {
            // 重定向到登录页
            resp.sendRedirect("/yjj/login.jsp");
        }
        /*String message = id!=null && id>0? "登录成功！":"登录失败！";
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(message);
        writer.flush();
        writer.close();*/

    }
}
